//
//  ViewController.swift
//  test
//
//  Created by lyl on 2019/12/12.
//  Copyright © 2019年 lyl. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    private var tf: UITextField!
    private var imageShowView: YLImageShowView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "查看", style: .plain, target: self, action: #selector(scan))
        
        addSubviews()
    }
    
    @objc func scan() {
        let vc = BViewController()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    private func addSubviews() {
        let urlTf = UITextField(frame: CGRect(x: contentMargin, y: 100, width: kCardWidth, height: 30))
        urlTf.textColor = color_51
        urlTf.font = font_14
        urlTf.textAlignment = .center
        urlTf.placeholder = "请输入网络地址"
        urlTf.text = "http://wamapi.com:8528/art-jibm/51950.html"
        view.addSubview(urlTf)
        tf = urlTf
        
        let btn = UIButton(frame: CGRect(x: (kScreenWidth-170)/2, y: urlTf.frame.maxY+50, width: 170, height: 44))
        btn.backgroundColor = .blue
        btn.setTitle("确定", for: .normal)
        btn.addTarget(self, action: #selector(selectPhoto), for: .touchUpInside)
        view.addSubview(btn)
        
        imageShowView = YLImageShowView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight))
        
    }
    
    @objc func selectPhoto() {
        tf.endEditing(true)
        //YLProgressHUD.showWait(view)
        if tf.text == "" {
            return
        }
        httpImgUrls(tf.text!)
    }
    
    
    func httpImgUrls(_ url: String) {
        //let str = "http://wamapi.com:8528/art-jibm/51952.html"// "http://news.163.com"
        print("fdfdgghhhh")
        do {
            //let encoding = CFStringConvertEncodingToNSStringEncoding(UInt32(CFStringEncodings.GB_18030_2000.rawValue))
        
            let html = try String(contentsOf: URL(string: url)!, encoding: String.Encoding.utf8)//String.Encoding(rawValue: encoding)
            print(html)
            let array = html.components(separatedBy: "\"")
            print(array)
            var imgHttps = [String]()
            for imgHttp in array {
                if imgHttp.hasSuffix(".jpg") {
                    imgHttps.append(imgHttp)
                }
            }
            print(imgHttps)
            imageShowView.setImgUrlArray(imgUrlArr: imgHttps)
            
            UIApplication.shared.keyWindow?.addSubview(imageShowView)
            
            //YLProgressHUD.hideHUDForView(view)
        } catch let error {
            print(error)
        }
        //return [String]()
    }
    
    
    
    
}

//Swift使用正则截取字符串的方法：
//匹配img标签的正则表达式为：
//<img\b(?=\s)(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?\ssrc=['"]([^"]*)['"]?)(?:[^>=]|='[^']*'|="[^"]*"|=[^'"\s]*)*"\s?\/?>
//    1
//    在swift中的正则表达式书写为：
//    let regex = "<img\\b(?=\\s)(?=(?:[^>=]|='[^']*'|=\"[^\"]*\"|=[^'\"][^\\s>]*)*?\\ssrc=['\"]([^\"]*)['\"]?)(?:[^>=]|='[^']*'|=\"[^\"]*\"|=[^'\"\\s]*)*\"\\s?\\/?>"
//    1
//    使用案例：
//    let string = "图片1<div><img src=\"http://cms-bucket.nosdn.127.net/catchpic/C/C7/C7643B52B98D04979AA173C6D6219958.jpg\" alt=\"Gravatar\"><br></div><div>图片2</div><div><img src=\"http://cms-bucket.nosdn.127.net/catchpic/C/C7/C7643B52B98D04979AA173C6D6219958.jpg\" alt=\"Gravatar\"><br></div><div><br></div><div>图片3</div><div><img src=\"http://cms-bucket.nosdn.127.net/catchpic/C/C7/C7643B52B98D04979AA173C6D6219958.jpg\" alt=\"Gravatar\"><br></div><div><br></div>"
//
//    // 截取img标签
//    let resultItems = string.matchesForRegex(regex)

//    截取得到的resultItems为:
//    ["<img src=\"http://cms-bucket.nosdn.127.net/catchpic/C/C7/C7643B52B98D04979AA173C6D6219958.jpg\" alt=\"Gravatar\">",
//    "<img src=\"http://cms-bucket.nosdn.127.net/catchpic/C/C7/C7643B52B98D04979AA173C6D6219958.jpg\" alt=\"Gravatar\">",
//    "<img src=\"http://cms-bucket.nosdn.127.net/catchpic/C/C7/C7643B52B98D04979AA173C6D6219958.jpg\" alt=\"Gravatar\">"]

//    如果单单只是截取img的url地址，使用的正则表达式为：
//    (http[^\s]+(jpg|jpeg|png|tiff)\b)
//    1
//    在Swift中书写为：
//    let regex = "(http[^\\s]+(jpg|jpeg|png|tiff)\\b)"
//    1
//    使用案例：
//    // 截取所有img url
//    let resultItems = string.matchesForRegex(regex)

//    结果为：
//    [“http://cms-bucket.nosdn.127.net/catchpic/C/C7/C7643B52B98D04979AA173C6D6219958.jpg”, “http://cms-bucket.nosdn.127.net/catchpic/C/C7/C7643B52B98D04979AA173C6D6219958.jpg”, “http://cms-bucket.nosdn.127.net/catchpic/C/C7/C7643B52B98D04979AA173C6D6219958.jpg”]



extension String {
    
    /**
     根据 正则表达式 截取字符串
     
     - parameter regex: 正则表达式
     
     - returns: 字符串数组
     */
    public func matchesForRegex(regex: String) -> [String]? {
        
        do {
            let regularExpression = try NSRegularExpression(pattern: regex, options: [])
            let range = NSMakeRange(0, self.count)
            let results = regularExpression.matches(in: self, options: [], range: range)
            let string = self as NSString
            return results.map { string.substring(with: $0.range)}
        } catch {
            return nil
        }
    }
}
